<template>
  <div class="forget-password">
    <div class="header">
      <div class="title">找回密码</div>
      <div>已有账号, <a href="javascript:;" @click="handleToLogin">马上登录</a></div>
    </div>
    <a-form
      :form="form"
    >
      <a-form-item>
        <a-input
          size="large"
          type="text"
          v-decorator="[
            'loginName',
            { rules: [{ required: true, message: '请输入账号!', whitespace: true, trigger: 'change' }] },
          ]"
          autocomplete="off"
          placeholder="请输入账号"
        >
          <a-icon slot="prefix" type="user" style="color: rgba(0,0,0,.25)" />
        </a-input>
      </a-form-item>
      <a-form-item>
        <a-input
          size="large"
          type="text"
          v-decorator="[
            'phone',
            { rules: [{ required: true, message: '请输入手机号码!', whitespace: true, trigger: 'change' }] },
          ]"
          autocomplete="off"
          placeholder="请输入手机号"
        >
          <a-icon slot="prefix" type="mobile" style="color: rgba(0,0,0,.25)" />
        </a-input>
      </a-form-item>
      <a-form-item>
        <a-input
          size="large"
          type="text"
          v-decorator="[
            'identify',
            { rules: [{ required: true, message: '', whitespace: true, trigger: 'change' }, { validator: validateSmsCode }] },
          ]"
          autocomplete="off"
          placeholder="请输入短信验证码">
          <a-icon slot="prefix" type="mail" style="color: rgba(0,0,0,.25)" />
          <span slot="suffix">
            <a-button type="link" :class="{ 'not-click': state.smsSendBtn }" size="small" @click.stop.prevent="handleSendCode">{{ state.codeText }}</a-button>
          </span>
        </a-input>
      </a-form-item>
      <a-form-item>
        <a-input-password
          size="large"
          type="password"
          v-decorator="[
            'password',
            { rules: [{ required: true, message: '', whitespace: true, trigger: 'change' }, { validator: validatePassword }] },
          ]"
          autocomplete="new-password"
          placeholder="请输入新密码">
          <a-icon slot="prefix" type="lock" style="color: rgba(0,0,0,.25)" />
        </a-input-password>
      </a-form-item>
      <a-form-item>
        <a-input-password
          size="large"
          v-decorator="[
            'qpassword',
            { rules: [{ required: true, message: '', whitespace: true, trigger: 'change' }, { validator: validateQPassword }] },
          ]"
          autocomplete="new-password"
          placeholder="请再次输入新密码">
          <a-icon slot="prefix" type="lock" style="color: rgba(0,0,0,.25)" />
        </a-input-password>
      </a-form-item>
      <a-form-item>
        <a-button
          type="primary"
          size="large"
          html-type="submit"
          class="login-form-sign"
          :loading="state.loginBtn"
          :disabled="state.loginBtn"
          @click="handleSubmit"
        >
          找回密码
        </a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script>
import md5 from 'md5'
import debounce from 'lodash.debounce'
import { updatePassword } from '@/api/system'
import { sendSmsCode, querySmsCode } from '@/api/common'
export default {
  name: 'ForgetPassword',
  data () {
    return {
      verifyCode: '',
      form: this.$form.createForm(this, { name: 'ForgetPassword' }),
      state: {
        time: 60,
        loginBtn: false,
        smsSendBtn: false,
        codeText: '获取验证码'
      }
    }
  },
  methods: {
    handleToLogin () {
      this.$parent.isForgetPassword = false
    },
    handleSendCode (e) {
      e.preventDefault()
      const { form: { validateFields } } = this

      validateFields(['phone', 'code'], { force: true }, (err, values) => {
        if (!err) {
          const { state, form: { getFieldValue } } = this
          state.smsSendBtn = true
          const interval = window.setInterval(() => {
            if (state.time-- <= 0) {
              state.time = 60
              state.smsSendBtn = false
              state.codeText = '获取验证码'
              window.clearInterval(interval)
            } else {
              state.codeText = `${state.time}秒后重新发送`
            }
          }, 1000)

          const hide = this.$message.loading('短信验证码正在发送中...', 0)
          sendSmsCode({ Phone: getFieldValue('phone') }).then(res => {
            setTimeout(hide, 100)
            this.$notification['success']({
              message: '提示',
              description: '短信验证码发送成功，可能会有延后请耐心等待',
              duration: 8
            })
          }).catch(err => {
            setTimeout(hide, 1)
            clearInterval(interval)
            state.time = 60
            state.smsSendBtn = false
            this.requestFailed(err)
          })
        }
      })
    },
    handleSubmit (e) {
      e.preventDefault()
      const { form: { validateFields, resetFields } } = this
      validateFields((err, values) => {
        if (!err) {
          updatePassword({
            NewPassword: md5(values.password),
            Phone: values.phone,
            LoginName: values.loginName
          }).then(res => {
            if (res.code === 200) {
              this.$notification['success']({
                message: '提示',
                description: '找回密码成功',
                duration: 8
              })
              resetFields()
              this.$parent.isForgetPassword = false
            } else {
              this.$message.error(res.msg)
            }
          }).catch((err) => {
            this.$notification['error']({
              message: '提示',
              description: err,
              duration: 8
            })
          })
        }
      })
    },
    querySmsCode: debounce(function (obj) {
      return new Promise((resolve, reject) => {
        querySmsCode(obj).then(res => {
          resolve(res)
        }).catch((err) => {
          reject(err)
        })
      })
    }, 500, { leading: false }),
    validateSmsCode (rule, value, callback) {
      const { form: { getFieldValue } } = this
      if (!value) {
        callback(new Error('请输入短信验证码!'))
      }
      if (value.length !== 6) {
        callback(new Error('验证码输入错误, 请重新输入!'))
      }
      if (getFieldValue('phone')) {
        this.querySmsCode({
          Phone: getFieldValue('phone'),
          YZM: value
        }).then(res => {
          if (res.code === 200) {
            callback()
          } else {
            callback(new Error('验证码输入有误'))
          }
        }).catch(() => {})
      } else {
        callback(new Error('请先输入手机号!'))
      }
      callback()
    },
    validatePassword (rule, value, callback) {
      if (!value) {
        callback(new Error('请输入密码!'))
      }
      callback()
    },
    validateQPassword (rule, value, callback) {
      const qpassword = this.form.getFieldValue('password')
      if (!value) {
        callback(new Error('请再次输入新密码!'))
      }
      if (value !== qpassword) {
        callback(new Error('两次输入的密码不一致,请检查后重新输入!'))
      }
      callback()
    }
  }
}
</script>

<style lang="less" scoped>
  .forget-password {
    .header {
      margin-bottom: 20px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .title {
        font-size: 20px;
      }
    }
    .login-form-sign {
      width: 100%;
    }
  }
</style>
